<?php

if (!defined('BASEPATH'))
	exit('No direct script access allowed');

define("EMPTY", " - ");
class Administration extends CI_Controller {

	//Doctrine EntityManager
	public $em;

	function __construct() {
		parent::__construct();

		//Not required if you autoload the library
		$this -> load -> library('doctrine');

		//Instantiate a Doctrine Entity Manager
		$this -> em = $this -> doctrine -> em;
		// $conn = $this->em->getConnection();
		//var_dump(models\service\CurrentUser::user());
		if (models\service\CurrentUser::user() == FALSE){
			header('location: ' . base_url());
		}
		
		// $conn->getDatabasePlatform()->registerDoctrineTypeMapping('enum', 'varchar');
	}
	
	
	// START USER
	public function userList($userId="", $msg=""){
		
		//$permission = $this->getPermission();
		$data['breadcrumb'] = array( array("label" => "Home", "link" => base_url("administration/userList")),
								 array("label" => "Pengaturan Pengguna", "link" => NULL)
								);
								
		$user = models\service\CurrentUser::user();								
		if ($userId != ""){
			$criteria = array('userId' => $userId);
			$selectedUser = $this->em->getRepository('\models\entities\User')->findOneBy($criteria);
			
		} else {
			$selectedUser = NULL;
		} 

		$serv = new models\service\AdministrationService;
		$indexAndCount[0] = 0;
		$indexAndCount[1] = 10;
		$data['users'] = $serv -> findAllUser($indexAndCount);
		$data['profiles'] = $this->em->getRepository('\models\entities\Profile')->findAll();
		$data['jabatans'] = $this->em->getRepository('\models\entities\Jabatan')->findAll();
		$data['selectedUser'] = $selectedUser;
		
		$data['user'] = $user;
		
		$criteria = array('userId' => $user->getUserId());
		$userProfiles = $this->em->getRepository('\models\entities\UserProfile')->findBy($criteria);
		$data['userProfiles'] = $userProfiles;
		
		$this -> load -> view('administration/user/index', $data);
	}
	
	public function saveUser(){
	/*	$permission = $this->getPermission();
		
		if (!in_array("009", $permission)){
			header('location: ' . base_url() . 'home'); 
		} */
		
		//echo "<pre>"; print_r($_POST);die();
		if ($this->input->post('User_userId') != NULL){
			$criteria = array('userId' => $this->input->post('User_userId') );
			$user = $this -> em -> getRepository('\models\entities\User') -> findOneBy($criteria);
			if (count($user) == 0){
				$user = new models\entities\User;
				$user->setUserId($this->input->post('User_userId'));
					
			} 
			
			$user->setPassword($this->input->post('User_password'));	
			$user->setName($this->input->post('User_name'));	
			$user->setMail($this->input->post('User_mail'));	
			$user->setStatus($this->input->post('User_status'));	
			$user->setCreateDate(new \DateTime('now', new \DateTimeZone("Asia/Jakarta")));
			$user->setMsisdn($this->input->post('msisdn'));			
			$criteria = array('id' => $this->input->post('User_Jabatan') );
			$jabatan = $this -> em -> getRepository('\models\entities\Jabatan') -> findOneBy($criteria);
			$user->setJabatan($jabatan);

			
			$i=0;
			$userProfiles = NULL;
			foreach ($this->input->post('User_Profil') as $up){
				$userProfile = new models\entities\UserProfile;
				//$userProfile->setUserId($user->getUserId);
				$criteria = array('id' => $up );
				$profile = $this -> em -> getRepository('\models\entities\Profile') -> findOneBy($criteria);
				$userProfile->setProfile($profile);
				$userProfiles[$i]=$userProfile;
				$i++;
			}	
			
			// $user->setName($this->input->post('User_name'));	
			// $user->setMail($this->input->post('User_mail'));	
			// $user->setStatus($this->input->post('User_status'));
			
			$serv = new models\service\AdministrationService;
			if ($serv->saveUser($user, $userProfiles)!==FALSE){
				header('location: ' . base_url().'administration/userList');	
			}
			else {
				header('location: ' . base_url().'administration/userList/'.$this->input->post('User_userId'));
			}
		}	
		die("NO DATA POST");	
	}
	
	public function deleteUser($id){
		$permission = $this->getPermission();
		
		if (!in_array("009", $permission)){
			header('location: ' . base_url() . 'home'); 
		}
		$criteria = array('userId' => $id);
		$user = $this -> em -> getRepository('\models\entities\User') -> findOneBy($criteria);
		
		$criteria = array('userId' => $id);
		$userProfile = $this -> em -> getRepository('\models\entities\UserProfile') -> findBy($criteria);
		
		$serv = new models\service\AdministrationService;
		
		if ($userProfile != NULL){
			foreach ($userProfile as $uprof){
				$this->em->remove($uprof);
				$this->em->flush();
			}	
		}
		
		
		$this->em->remove($user);
		$this->em->flush();
		
		header('location: ' . base_url().'home/userList');
	}
	// END USER	
	
	// START PROFILE
	public function profileList(){
		$permission = $this->getPermission();
		
		if (!in_array("009", $permission)){
			header('location: ' . base_url() . 'home'); 
		}
		$data['breads'] = array( array("label" => "Home", "link" => base_url() . "Dashboard"));

		$serv = new models\service\FinanceService;
		$indexAndCount[0] = 0;
		$indexAndCount[1] = 10;

		$data['profiles'] = $serv -> findAllProfiles($indexAndCount);
		
		$this -> load -> view('profile', $data);
	}
	
	public function createProfile($id=0, $step=-1){
		$permission = $this->getPermission();
		
		if (!in_array("009", $permission)){
			header('location: ' . base_url() . 'home'); 
		}
		$data['breads'] = array( array("label" => "Home", "link" => base_url() . "Dashboard"));
		$data['id'] = $id;
		$data['step'] = $step;
		$profiles = $this->em->getRepository('\models\entities\Profile')->findAll();
		if ($id>0){
			$criteria = array('id' => $id);
			$profile = $this -> em -> getRepository('\models\entities\Profile') -> findOneBy($criteria);
			$criteria = array('profile' => $profile);
			$profilePerms = $this -> em -> getRepository('\models\entities\UserProfilePermission') -> findBy($criteria);	
		} else {
			$profile = NULL;
			$profilePerms = NULL;
		}
		$data['permissions'] = $this->em->getRepository('\models\entities\Permission')->findAll();
		$data['profiles'] = $profiles;
		$data['profile'] = $profile;
		$data['profilePerms'] = $profilePerms;
		$this -> load -> view('createProfile', $data);		
	}
	
	public function saveProfile(){
		$permission = $this->getPermission();
		
		if (!in_array("009", $permission)){
			header('location: ' . base_url() . 'home'); 
		}
		if ($this->input->post('id') != NULL){
			if ($this->input->post('id') > 0){
				$criteria = array('id' => $this->input->post('id'));
				$profile = $this -> em -> getRepository('\models\entities\Profile') -> findOneBy($criteria);
				
				$criteria = array('profile' => $profile);
				$upp = $this -> em -> getRepository('\models\entities\UserProfilePermission') -> findBy($criteria);				
			} else {
				
				$profile = new models\entities\Profile;
				$upp = NULL;
			}
			
			$perms = $this->input->post('perm');
			$profile->setNamaProfile($this->input->post('name'));
			$this -> em -> persist($profile);
			$this -> em -> flush();
			
			// cek userProfilePermission
			if ($upp != NULL){
				// delete all permission
				foreach ($upp as $up){
					$this -> em -> remove($up);
					$this -> em -> flush();
				}
			}
			
			foreach ($perms as $perm){
					$upp = new models\entities\UserProfilePermission;					
					$upp->setProfile($profile);
					$criteria = array('code' => $perm);
					$permission = $this -> em -> getRepository('\models\entities\Permission') -> findOneBy($criteria);
					$upp->setPermission($permission);
					$this -> em -> persist($upp);
					$this -> em -> flush();	
			}
		}
		header('location: ' . base_url().'home/createProfile');
	}

	public function deleteProfile($id){
		$permission = $this->getPermission();
		
		if (!in_array("009", $permission)){
			header('location: ' . base_url() . 'home'); 
		}
		$criteria = array('id' => $id);
		$profile = $this -> em -> getRepository('\models\entities\Profile') -> findOneBy($criteria);
		
		$criteria = array('profile' => $profile);
		$userProfile = $this -> em -> getRepository('\models\entities\UserProfile') -> findBy($criteria);
		
		$criteria = array('profile' => $profile);
		$userProfilePermission = $this -> em -> getRepository('\models\entities\UserProfilePermission') -> findBy($criteria);
		
		if ($userProfilePermission !=NULL){
			foreach ($userProfilePermission as $upp){
				$this -> em -> remove($upp);
				$this -> em -> flush();
			}	
		}
		
		if ($userProfile != NULL){
			foreach ($userProfile as $uprof){
				$this->em->remove($uprof);
				$this->em->flush();
			}	
		}
		
		$this->em->remove($profile);
		$this->em->flush();
		
		header('location: ' . base_url().'home/createProfile');
	}
	// END PROFILE
	
	//START PROPINSI
	//List All Propinsi Controller
	public function propinsiList($propinsiId="", $msg=""){
		
		//$permission = $this->getPermission();
		$data['breadcrumb'] = array( array("label" => "Home", "link" => NULL),
								 array("label" => "Pengaturan Pengguna", "link" => NULL)
								);
								
		$user = models\service\CurrentUser::user();								
		if ($propinsiId != ""){
			$criteria = array('id' => $propinsiId);
			$selectedPropinsi = $this->em->getRepository('\models\entities\Propinsi')->findOneBy($criteria);
			
		} else {
			$selectedPropinsi = NULL;
		} 

		$serv = new models\service\AdministrationService;
		$indexAndCount[0] = 0;
		$indexAndCount[1] = 10;
		$data['propinsis'] = $this->em->getRepository('\models\entities\Propinsi')->findAll();
		$data['propinsi'] = $selectedPropinsi;
		$data['user'] = $user;
		
		$criteria = array('userId' => $user->getUserId());
		$userProfiles = $this->em->getRepository('\models\entities\UserProfile')->findBy($criteria);
		$data['userProfiles'] = $userProfiles;
		$this -> load -> view('administration/propinsi/index', $data);
	}
	// END OF List All Propinsi Controller
	
	//SAVE Propinsi Controller
	public function savePropinsi(){
		if ($this->input->post('Propinsi_nama') != NULL){
			$param['Propinsi']['nama'] = $this->input->post('Propinsi_nama');
			$param['Propinsi']['id'] = $this->input->post('Propinsi_id');
			$serv = new models\service\AdministrationService;
			if ($serv->savePropinsi($param)!==FALSE){
				header('location: ' . base_url().'administration/propinsiList');	
			}
		}	
		die("NO DATA POST");	
	}
	
	// END OF SAVE Propinsi Controller
	
	public function distrikList($distrikId="", $msg=""){
		
		//$permission = $this->getPermission();
		$data['breadcrumb'] = array( array("label" => "Home", "link" => NULL),
								 array("label" => "Pengaturan Pengguna", "link" => NULL)
								);
								
		$user = models\service\CurrentUser::user();								
		if ($distrikId != ""){
			$criteria = array('id' => $distrikId);
			$selectedDistrik = $this->em->getRepository('\models\entities\Distrik')->findOneBy($criteria);
			
		} else {
			$selectedDistrik = NULL;
		} 
		
		$serv = new models\service\AdministrationService;
		$indexAndCount[0] = 0;
		$indexAndCount[1] = 10;
		$data['distriks'] = $this->em->getRepository('\models\entities\Distrik')->findAll();

		$data['selectedDistrik'] = $selectedDistrik;
		$data['distrik'] = $selectedDistrik;
		$data['propinsis'] = $this->em->getRepository('\models\entities\Propinsi')->findAll();
		$data['user'] = $user;
		
		$criteria = array('userId' => $user->getUserId());
		$userProfiles = $this->em->getRepository('\models\entities\UserProfile')->findBy($criteria);
		$data['userProfiles'] = $userProfiles;
		$this -> load -> view('administration/distrik/index', $data);
	}
	
	public function saveDistrik(){
	echo "<pre>";print_r($_POST);
		echo "<pre>";print_r($_FILES);
		
		if ($this->input->post('Distrik_nama') != NULL){
			$param['Distrik']['nama'] = $this->input->post('Distrik_nama');
			$param['Distrik']['id'] = $this->input->post('Distrik_id');
			$param['Distrik']['propinsi'] = $this->input->post('Distrik_propinsi');
			$serv = new models\service\AdministrationService;
			if ($serv->saveDistrik($param)!==FALSE){
				header('location: ' . base_url().'administration/distrikList');	
			}
		}
		else
		{
		die("NO DATA POST");	
		}
	}
	//FORM CHANGE PASS
	public function formChangePassword($userId="", $msg=""){
		
		//$permission = $this->getPermission();
		$data['breadcrumb'] = array( array("label" => "Home", "link" => NULL),
								 array("label" => "Pengaturan Pengguna", "link" => NULL)
								);
								
		$user = models\service\CurrentUser::user();								
		$data['user'] = $user;
		
		$criteria = array('userId' => $user->getUserId());
		$userProfiles = $this->em->getRepository('\models\entities\UserProfile')->findBy($criteria);
		$data['userProfiles'] = $userProfiles;
		$this -> load -> view('administration/user/formChangePassword', $data);
	}
	
	public function changePassword(){
		if ($this->input->post('User_userId') != NULL && $this->input->post('User_password') != NULL && $this->input->post('User_confirmPassword') != NULL && $this->input->post('User_oldPassword')!= NULL){
			$user = models\service\CurrentUser::user();		
			$param['User']['userId'] = $this->input->post('User_userId');
			$param['User']['password'] = $this->input->post('User_password');
			$param['User']['confirmPassword'] = $this->input->post('User_confirmPassword');
			$param['User']['oldPassword'] = $this->input->post('User_oldPassword');
			$param['User']['loggingIn'] = $user->getUserId();
			$serv = new models\service\AdministrationService;
			if ($serv->changePassword($param)!==FALSE){
				$this->session->set_userdata('flash_message',MESSAGE_PROFILE_CHANGEPASS_SUCCESS);
				header('location: ' . base_url().'administration/formChangePassword');	
			} else {
				header('location: ' . base_url().'administration/formChangePassword');
			}
		}
		else
		{
			die("NO DATA POST");	
		}
	}
	
	public function getPermission(){
		$username = $this->session->userdata('user_id');
		$criteria = array('userId' => $username);
		$uprofile = $this->em->getRepository('\models\entities\UserProfile')->findOneBy($criteria);
						
		$criteria = array('profile' => $uprofile->getProfile());
		$ups = $this->em->getRepository('\models\entities\UserProfilePermission')->findBy($criteria); 
		$permission = array();
		foreach ($ups as $up){
			$permission[] = $up->getPermission()->getCode();
		}
		return $permission;
	}	
}

